<?php
namespace app\lib;

use app\constdir\ApiConst;
use think\Cache;

require_once '../extend/alipay/aop/AopClient.php';
require_once '../extend/alipay/aop/AopCertClient.php';
require_once '../extend/alipay/aop/AopCertClient.php';
require_once '../extend/alipay/aop/request/AlipayFundTransUniTransferRequest.php';

class Alipay
{
    private $customKey = ALIPAY_CUSTOM_KEY;
    //https://open.alipay.com 账户中心->密钥管理->开放平台密钥，填写添加了“单笔转账到账户”应用的APPID
    private $appId = ALIPAY_APP_ID;
    //签名算法类型，支持RSA2和RSA，推荐使用RSA2
    private $signType = ALIPAY_SIGN_TYPE;
    //商户私钥，填写对应签名算法类型的私钥，如何生成密钥参考：https://docs.open.alipay.com/291/105971和https://docs.open.alipay.com/200/105310
    private $rsaPrivateKey = ALIPAY_RSA_PRIVATE_KEY;
    private $gatewayUrl = ALIPAY_GATEWAY_URL;
    //应用公钥证书
    private $appCertPath = ALIPAY_APP_CERT_PATH;
    //支付宝公钥证书
    private $alipayCertPath = ALIPAY_ALIPAY_CERT_PATH;
    //支付宝根证书(此处由于根证书用支付宝给于的方法进行解析有问题，故用的支付宝官方提供的固定值进行验证，此固定值有效期2028年)
    private $rootCertPath = ALIPAY_ROOT_CERT_PATH;
    private $alipayRootCertSN = ALIPAY_ROOT_CERT_SN;

    public function getCheckObj(){
        $c = new \AopCertClient();
        $c->gatewayUrl = $this->gatewayUrl;
        $c->appId = $this->appId;
        $c->rsaPrivateKey = $this->rsaPrivateKey;
        $c->format = "json";
        $c->charset= "GBK";
        $c->signType= $this->signType;

        //调用getPublicKey从支付宝公钥证书中提取公钥
        $c->alipayrsaPublicKey = $c->getPublicKey($this->alipayCertPath);
        //是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
        $c->isCheckAlipayPublicCert = true;
        //调用getCertSN获取证书序列号
        $c->appCertSN = $c->getCertSN($this->appCertPath);

        //调用getRootCertSN获取支付宝根证书序列号
        //$c->alipayRootCertSN = $c->getRootCertSN($this->rootCertPath);
        $c->alipayRootCertSN = $this->alipayRootCertSN;

        return $c;
    }


    /**
     * @auther zlq
     * @create_time 2020/6/17 15:28
     * @description 进行转账操作
     * @throws \Exception
     */
    public function transferAccountToWorker($msg = [])
    {
        if(empty($msg['worker_phone'])){
            return ['status' => ApiConst::ALIPAY_PHONE_ERROR, 'msg' => ApiConst::ALIPAY_PHONE_ERROR_MSG, 'data' => []];
        }
        $getCustomKey = Cache::get($msg['worker_phone']);
        $md5Key = md5($msg['worker_phone'].$this->customKey);
        if($getCustomKey !== $md5Key){
            return ['status' => ApiConst::ALIPAY_BASE_ERROR, 'msg' => ApiConst::ALIPAY_BASE_ERROR_MSG, 'data' => []];
        }
        $request = new \AlipayFundTransUniTransferRequest();
        $data['out_biz_no'] = $msg['out_biz_no'];
        // 工资范围 [0.1,100000000]
        $data['trans_amount'] = $msg['trans_amount'];
        $data['product_code'] = 'TRANS_ACCOUNT_NO_PWD';
        $data['biz_scene'] = 'DIRECT_TRANSFER';
        $data['order_title'] = isset($msg['order_title']) ? $msg['order_title'] : '任务单工资发放';
        // $data['original_order_id'] = ;
        $data['payee_info'] = [
            'identity' => $msg['worker_phone'],
            'identity_type' => 'ALIPAY_LOGON_ID',
            'name' => $msg['worker_name'],
        ];
        $data['remark'] = isset($msg['remark']) ? $msg['remark'] : '任务单工资发放';
        // $data['business_params'] = ['sub_biz_scene' => "REDPACKET"];
        $param = json_encode($data);
        $request->setBizContent($param);
        $result = $this->getCheckObj()->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        // 判断异常
        $resultCode = $result->$responseNode->code;
        if ($resultCode != 10000) {
            session('error_msg', $result->$responseNode->sub_msg);
            return ['status' => 0, 'msg' => $result->$responseNode->sub_msg, 'data' => []];
        }
        $status = $result->$responseNode->status;
        if(!empty($resultCode) && $resultCode == 10000){
            $res_array = [
                'code' => $resultCode,
                'msg' => $msg,
                'order_id' => $result->$responseNode->order_id,
                'out_biz_no' => $result->$responseNode->out_biz_no,
                'pay_fund_order_id' => $result->$responseNode->pay_fund_order_id,
                'status' => $status,
                'trans_date' => $result->$responseNode->trans_date,
            ];
            return ['status' => 1, 'msg' => $status, 'data' => $res_array];
        } else {
            return ['status' => 0, 'msg' => $status, 'data' => []];
        }
    }



}